var shopId

function outputId(id) {
    shopId = id
}

function deleteItem() {
    $.ajax({
        url: "/cart/deleteByFoodId", dataType: "json", data: {
            foodid: shopId
        }, success: function (data) {
            console.log(data);
        }
    })
}

function ShoppingCarObserver(elInput, isAdd) {
    this.elInput = elInput
    this.parents = this.elInput.parents('.goods-item')
    this.count = parseInt(this.elInput.val())
    this.isAdd = isAdd
    this.singlePrice = parseFloat(this.parents.find('.single-price').text())
    this.computeGoodsMoney = function () {
        var moneyCount = this.count * this.singlePrice
        var singleTotalEl = this.parents.find('.single-total')
        console.log(moneyCount)
        singleTotalEl.empty().append(moneyCount)
    }
    this.showCount = function () {
        var isChecked = this.parents.find('.goods-list-item')[0].checked
        var GoodsTotalMoney = parseFloat($('#selectGoodsMoney').text())
        var goodsTotalCount = parseInt($('#selectGoodsCount').text())
        if (this.elInput) {
            if (this.isAdd) {
                ++this.count
                if (isChecked) {
                    $('#selectGoodsMoney').empty().append(GoodsTotalMoney + this.singlePrice)
                    $('#selectGoodsCount').empty().append(goodsTotalCount + 1)
                }
            } else {
                if (parseInt(this.count) <= 1) {
                    return
                } else {
                    --this.count
                    if (isChecked) {
                        $('#selectGoodsMoney').empty().append(GoodsTotalMoney - this.singlePrice)
                        $('#selectGoodsCount').empty().append(goodsTotalCount - 1)
                    }
                }
            }
            this.elInput.val(this.count)
        }
    }
    this.checkIsAll = function () {
        var checkLen = $('.goods-list-item:checked').length
        if (checkLen > 0) {
            $('.submitData').removeClass('submitDis')
        } else {
            $('.submitData').addClass('submitDis')
        }
        if ($('.goods-item').length === checkLen) {
            $('#checked-all-bottom, #check-goods-all').prop('checked', true)
        } else {
            $('#checked-all-bottom, #check-goods-all').prop('checked', false)
        }
    }
    this.checkedChange = function (isChecked) {
        if (isChecked === undefined) {
            var isChecked = this.parents.find('.goods-list-item')[0].checked
        }
        var itemTotalMoney = parseFloat(this.parents.find('.single-total').text())
        var GoodsTotalMoney = parseFloat($('#selectGoodsMoney').text())
        var itemCount = parseInt(this.parents.find('.goods-count').val())
        var goodsTotalCount = parseInt($('#selectGoodsCount').text())
        if (isChecked) {
            $('#selectGoodsMoney').empty().append(itemTotalMoney + GoodsTotalMoney)
            $('#selectGoodsCount').empty().append(itemCount + goodsTotalCount)
        } else {
            if (GoodsTotalMoney - itemTotalMoney === 0) {
                $('#selectGoodsMoney').empty().append('0.00')
                if (!$('.submitData').hasClass('submitDis')) {
                    $('.submitData').addClass('submitDis')
                }
            } else {
                $('#selectGoodsMoney').empty().append(GoodsTotalMoney - itemTotalMoney)
            }
            $('#selectGoodsCount').empty().append(goodsTotalCount - itemCount)
        }
    }
    this.deleteGoods = function () {
        var isChecked = this.parents.find('.goods-list-item')[0].checked
        if (isChecked) {
            this.checkedChange(false)
        }
        this.parents.remove()
        this.checkOptions()
    }
    this.checkOptions = function () {
        if ($('#check-goods-all')[0].checked) {
            if ($('.goods-list-item').length <= 0) {
                $('#checked-all-bottom, #check-goods-all').prop('checked', false)
            }
        }
    }
}

function checkedAll(_this) {
    if ($('.goods-item').length <= 0) {
        $('.submitData').addClass('submitDis')
    } else {
        $('.submitData').removeClass('submitDis')
    }
    for (var i = 0; i < $('.goods-item').length; i++) {
        var elInput = $('.goods-item').eq(i).find('.goods-list-item')
        var isChecked = $('.goods-item').eq(i).find('.goods-list-item')[0].checked
        var checkAllEvent = new ShoppingCarObserver(elInput, null)
        if (_this.checked) {
            if (!isChecked) {
                elInput.prop('checked', true)
                checkAllEvent.checkedChange(true)
            }
        } else {
            if (!$('.submitData').hasClass('submitDis')) {
                $('.submitData').addClass('submitDis')
            }
            if (isChecked) {
                elInput.prop('checked', false)
                checkAllEvent.checkedChange(false)
            }
        }
    }
}

$('#check-goods-all').on('change', function () {
    if (this.checked) {
        $('#checked-all-bottom').prop('checked', true)
    } else {
        $('#checked-all-bottom').prop('checked', false)
    }
    checkedAll(this)
})
/*点击所有*/
$('#checked-all-bottom').on('change', function () {
    if (this.checked) {
        $('#check-goods-all').prop('checked', true)
    } else {
        $('#check-goods-all').prop('checked', false)
    }
    checkedAll(this)
})
$('.goods-list-item').on('change', function () {
    var tmpCheckEl = $(this)
    var checkEvent = new ShoppingCarObserver(tmpCheckEl, null)
    checkEvent.checkedChange()
    checkEvent.checkIsAll()
})
/*点击减少数量*/
$('.goods-content').on('click', '.car-decrease', function () {
    let goodsInput = $(this).parents('.input-group').find('.goods-count')
    let decCount = new ShoppingCarObserver(goodsInput, false)
    $.ajax({
        url: "/cart/setCount", dataType: "json", data: {
            foodid: shopId, count: -1,
        }, success: function (res) {
            console.log("des：" + res)
        }
    })
    decCount.showCount()
    decCount.computeGoodsMoney()
})

/*点击增加数量*/
$('.goods-content').on('click', '.car-add', function () {
    let goodsInput = $(this).parents('.input-group').find('.goods-count')
    let addCount = new ShoppingCarObserver(goodsInput, true)
    $.ajax({
        url: "/cart/setCount", dataType: "json", data: {
            foodid: shopId, count: 1,
        }, success: function (res) {
            console.log("add：" + res)
        }
    })
    addCount.showCount()
    addCount.computeGoodsMoney()
})

$('.goods-content').on('click', '.item-delete', function () {
    var goodsInput = $(this).parents('.goods-item').find('.goods-list-item')
    deleteGoods = new ShoppingCarObserver(goodsInput, null)
    $('#deleteItemTip').modal('show')
})

$('.deleteSure').on('click', function () {
    if (deleteGoods !== null) {
        deleteGoods.deleteGoods()
        deleteItem()
    }
    $('#deleteItemTip').modal('hide')
})
$('#deleteMulty').on('click', function () {
    if ($('.goods-list-item:checked').length <= 0) {
        $('#selectItemTip').modal('show')
    } else {
        $('#deleteMultyTip').modal('show')
    }
})
$('.deleteMultySure').on('click', function () {
    for (var i = 0; i < $('.goods-list-item:checked').length; i++) {
        var multyDelete = new ShoppingCarObserver($('.goods-list-item:checked').eq(i), null)
        multyDelete.deleteGoods()
        i--
    }
    multyDelete.checkOptions()
    $('#deleteMultyTip').modal('hide')
})

function setCount(foodid) {
    let selector = "#price" + foodid;
    let selector1 = "#count" + foodid;
    let selector2 = "#prices" + foodid;
    let $price = $(selector);
    let $count = $(selector1);
    let $prices = $(selector2);
    $.ajax({
        url: '/cart/setCount', data: {
            foodid: foodid, 'count': $count.val()
        }
    })
    $prices.text(parseInt($price.text()) * $count.val())
}

function showLocation(province, city, town) {
    var loc = new Location();
    var title = ['省份', '地级市', '市、县、区'];
    $.each(title, function (k, v) {
        title[k] = '<option value="">' + v + '</option>';
    })

    $('#loc_province').append(title[0]);
    $('#loc_city').append(title[1]);
    $('#loc_town').append(title[2]);

    $("#loc_province,#loc_city,#loc_town").select2()
    $('#loc_province').change(function () {
        $('#loc_city').empty();
        $('#loc_city').append(title[1]);
        loc.fillOption('loc_city', '0,' + $('#loc_province').val());
        $('#loc_city').change()
    })

    $('#loc_city').change(function () {
        $('#loc_town').empty();
        $('#loc_town').append(title[2]);
        loc.fillOption('loc_town', '0,' + $('#loc_province').val() + ',' + $('#loc_city').val());
    })

    $('#loc_town').change(function () {
        $('input[name=location_id]').val($(this).val());
    })

    if (province) {
        loc.fillOption('loc_province', '0', province);

        if (city) {
            loc.fillOption('loc_city', '0,' + province, city);

            if (town) {
                loc.fillOption('loc_town', '0,' + province + ',' + city, town);
            }
        }

    } else {
        loc.fillOption('loc_province', '0');
    }
}

$(function () {
    showLocation();
    /*结算按钮*/
    let $settlement = $("#settlement");
    $settlement.on("click", function () {
        if (!$settlement.hasClass("submitDis")) {
            let province = $('#loc_province').select2('data').text;
            let city = $('#loc_city').select2('data').text;
            let town = $('#loc_town').select2('data').text;
            let detail = $('#detail').val().trim();
            if (province === '省份') {
                alert("请填写省份")
                return;
            }
            if (city === '地级市') {
                alert("请填写地级市")
                return;
            }
            if (town === '市、县、区') {
                alert("请填写市、县、区")
                return;
            }
            if (detail === '') {
                alert("请填写详细地址")
                return;
            }
            let address = province + city + town + detail;
            let total_price = parseFloat($("#selectGoodsMoney").text());
            let put = [];
            /*2.0获取所有被选择的checked,然后获取它的id，这个id就是菜品id*/
            $(".goods-item").each(function () {
                let item = $(this);
                let isChecked = item.find(".goods-list-item").prop('checked');
                if (isChecked) {
                    let name = item.find(".goods-info").text().trim();
                    let price = item.find(".single-price").text().trim();
                    let count = item.find(".goods-count").val().trim();
                    let totalPrice = item.find(".single-total").text().trim();
                    console.log(name, price, count, total_price)
                    let order_detail = {
                        'name': name,
                        'price': price,
                        'count': count,
                        'totalPrice': totalPrice
                    }
                    put.push(order_detail)
                }
            })
            if (total_price <= 0.0) {
                alert("出错了，请刷新页面或者重新登录")
                return;
            }
            /*筛选链的最后*/
            $.ajax({
                url: '/addOrder.do',
                data: {
                    'address': address,
                    'price': total_price,
                    'put' : JSON.stringify(put),
                },
                dataType: "text", success: function (response) {
                    if (response === '1') {
                        window.location.href="/user_order.html"
                    } else {
                        alert("订单创建失败，请稍后再尝试");
                    }
                }
            });
        } else {
            alert("请勾选商品后再选择下单")
        }
    })
})

;